package com.bw.controller;

import com.bw.entity.UserInfo;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/loginPage.do")
    public String loginPage() {
        return "login";
    }



    @RequestMapping("/login.do")
    public String login(@Valid UserInfo loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {

       if (result.hasErrors()){
           model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());

           return "login";
       }
       // 用户名是否存在
        UserInfo userFromDB =
                userMapper.selectByName(loginUser.getName());

       if (userFromDB == null){
           model.addAttribute("error","用户名不存在");
           return "login";
       }
       // 密码是否正确
        String loginUserPassword = loginUser.getPassword();// 用户登录在页面输入的密码

        String password = userFromDB.getPassword(); //数据库里的乱码  （123qwe 加密生成）
        String salt = userFromDB.getSalt(); //数据库里的盐

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);// 加密用户输入的密码 和数据库里的盐
        //  判断两个乱码是否相等
        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";
        }

        // 制作令牌  用jwt加密用户信息得到token  把token放入cookie  把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userFromDB,response);

        return "success";
    }

}
